/*
 * @Author: chengpengfei
 * @Date: 2023-01-31 14:32:12
 * @LastEditors: chengpengfei
 * @LastEditTime: 2023-02-14 14:43:59
 * @Description:
 */
use std::{
    fs::{remove_file, File},
    io::{Read, Write},
};
use libharu::{
    self,
    prelude::{
        CompressionMode, Document, PageDescTeextCommonFunction, PageDescriptionMode, PageMode,
    },
    Point,
};

use crate::{types::structs::Table, utils::text_render::TextCanvas};

pub fn run(text_table: Table, saved_file_name: String) -> Vec<u8> {
    let text_canvas = TextCanvas::new();
    let height = ((text_table.body.len() + 1) * 32) as f32;
    let width_info = text_table.get_col_width_percent(&|str| text_canvas.get_text_width(str));
    let mut max_width = 0.0;
    let doc = Document::new(|err| println!("发生错误：{:?}", err)).expect("创建pdf时发生错误");
    doc.set_compression_mode(CompressionMode::ALL).expect("");
    doc.use_cnsencodings().expect("");
    doc.use_cnsfonts().expect("设置中文字体失败");
    doc.use_utfencodings().expect("");
    doc.set_current_encoder("UTF-8").expect("");
    doc.set_page_mode(PageMode::Outline).expect("");
    let font_name = doc
        .load_ttf_font_from_ttc("C:/Windows/Fonts/msyh.ttc", 1, true)
        .expect("加载字体失败");
    let bold_font_name=doc.load_ttf_font_from_ttc("C:/Windows/Fonts/msyhbd.ttc", 1, true).expect("粗体加载失败");
    let font = doc.font(font_name, Some("UTF-8")).expect("msg");
    let bold_font=doc.font(bold_font_name, Some("UTF-8")).expect("粗体字体加载失败");
    let page = doc.add_page().expect("创建页面失败");
    let page = PageDescriptionMode::new(&page);
    page.set_height(height).expect("page高度设定失败");
    page.set_font_and_size(&font, 16.0)
        .expect("page设置字体失败");

    let mut point = Point {
        x: 10.0,
        y: height - 30.0,
    };
    let mut index = 0;
    page.set_font_and_size(&bold_font, 24.0).unwrap();
    for cell in text_table.head {
        // println!("{}，{:?}", cell, point);
        page.run_text_mode(|page| {
            page.move_text_pos(point).expect("移动位置失败");
            page.show_text(&cell.to_string()).expect("设置文本失败");
            Ok(())
        })
        .expect("");
        point.x = point.x + width_info.widths[index] as f32;
        index += 1
    }
    page.set_font_and_size(&font, 16.0).unwrap();

    for row in text_table.body {
        point.x = 10.0;
        point.y = point.y - 30.0;
        // println!("{}，{:?}", row[0], point);
        let mut index = 0;
        for cell in row {
            page.run_text_mode(|page| {
                page.move_text_pos(point).expect("body");
                page.show_text(&cell).expect("");
                Ok(())
            })
            .expect("");
            if index == 3 {
                let end_point_x = point.x + text_canvas.get_text_width(cell) as f32 +24.0;
                if end_point_x > max_width as f32 {
                    max_width = end_point_x as f32;
                }
            }
            point.x = point.x + width_info.widths[index] as f32;
            index += 1;
        }
    }
    page.set_width(max_width+20.0).expect("设定宽度失败");

    // let file_path=Path::new(&saved_file_name).to_str().unwrap();
    // println!("选择的地址{:?}",file_path);
    doc.save_to_file("temp.pdf").expect("pdf文件创建失败");
    let mut buffer = Vec::new();
    File::open("temp.pdf")
        .unwrap()
        .read_to_end(&mut buffer)
        .unwrap();
    remove_file("temp.pdf").unwrap();
    let mut file = File::create(saved_file_name).expect("创建用户指定的pdf失败");
    file.write_all(&mut buffer)
        .expect("为用户指定的pdf写入数据失败");
    return buffer;
}
